<script lang="ts" setup>
// import { marked } from 'marked'
import type { FormInstance, RequestOption } from '@arco-design/web-vue'
// import type { DomainItem } from '@/apis/model/resolve'
import { postCdnVersionUploadCompleteApi } from '@/apis/modules/cdn.ts'
import useUpload from '@/views/cdn/node/node-version/hooks/useUpload'

withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])
// import { v4 as uuidV4 } from 'uuid'
interface IProp {
  record?: any
}
let pollIntervalId

const {
  percentage,
  resolving,
  uploadError,
  initTus,
  startOrResumeUpload,
  pauseUpload,
} = useUpload()

// const markdownContent = ref('')
const fileList = ref<any[]>([])
const errorTipText = ref('上传失败，请重新上传')
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
// const dnsNameOptions = ref<LabelValue[]>([])
const formState = ref({
  imprint: '',
  version: '',
  file_key: '',
  file: undefined,
  id: undefined,
})
// 上传的文件
const loading = ref<boolean>(false)
const showProgress = computed(
  () => percentage.value !== 0 && percentage.value !== 100 && !uploadError.value,
)
const baseUrl = computed(() => {
  return import.meta.env.VITE_HTTP_API
})

// 上传组件
function customRequest(option: RequestOption) {
  const { fileItem } = option
  const file = fileItem.file!
  initTus({
    endpoint: `${baseUrl.value}/v1/cdn/node/version/tus`,
    chunkSize: 5 * 1024 * 1024,
    file,
    afterSuccess: getAnalysisState,
  })
  startOrResumeUpload()
  // if (file) {
  //   uploadFile(file)
  // }
}
// 上传
// async function uploadFile(file: File) {
//   try {
//     // 1. 初始化上传
//     const { upload_id, part_size, object_key } = await initUpload(file)
//     // 2. 上传所有分片
//     const { etag } = await uploadChunks(file, upload_id, part_size, object_key)
//     console.log('etag', etag)
//     // // 3. 完成上传
//     // const result = await completeUpload(etag)

//     console.log('上传成功', result)
//     return result
//   } catch (error) {
//     console.error('上传失败', error)
//     throw error
//   }
// }

// 初始化分片上传
// async function uploadFile(file: File) {
//   const response = await addCdnVersionUploadInitApi({ filename: file.name, size: file.size })
//   const data = await response
//   return data
// }

// // 分片上传
// async function uploadChunks(file: File, upload_id: string, part_size: string, object_key: string) {
//   const partSize = Number.parseInt(part_size)
//   const chunkCount = Math.ceil(file.size / partSize)
//   // const promises = []

//   for (let i = 0; i < chunkCount; i++) {
//     const start = i * partSize
//     const end = Math.min(file.size, start + partSize)
//     const chunk = file.slice(start, end)
//     // const formData = new FormData()
//     // formData.append(chunk)
//     // console.log(formData)
//     // promises.push(
//     //   putCdnVersionUploadPartApi({ upload_id, part_number: i, object_key, body: formData }),
//     //   // fetch('/api/upload/chunk', {
//     //   //   method: 'POST',
//     //   //   body: formData,
//     //   // }),
//     // )
//     // percentage.value = Math.floor((start + 1) / partSize * 100)
//     percentage.value = Math.floor((start + 1) / file.size * 100)
//     await fetch(`${baseUrl.value}/v1/cdn/node/version/upload/part/binary?upload_id=${upload_id}&object_key=${object_key}&part_number=${i}`, {
//       method: 'PUT',
//       headers: {
//         'Content-Type': 'application/octet-stream',
//         // 'Upload-Offset': start, // 设置当前分片的起始位置
//       },
//       body: chunk, // 直接使用Blob作为body
//     })
//   }

//   return Promise.all(promises)
// }

// // 完成上传
// async function completeUpload(etag) {
//   console.log(etag)
//   const data = await postCdnVersionUploadCompleteApi({ upload_id, object_key })
//   console.log(data)
//   if (data.code === 200) {
//     successfulType.value = true
//     resolving.value = true
//     percentage.value = 100
//   }
// }

const successfulType = ref(false)

function getAnalysisState(data: string) {
  const actualId = data.split('+')[0].split('/').pop()
  const id = `node/version/tmp/${actualId}`
  resolving.value = true
  pollIntervalId = setInterval(getForAnalysisDetail, 1500, id)
  getForAnalysisDetail(id)
  // getDetail(data)
}

function beforeUpload() {
  successfulType.value = false
  resolving.value = false
  // 上传前的校验逻辑
  return true
}

function getForAnalysisDetail(id: string) {
  // loading.value = true
  postCdnVersionUploadCompleteApi({
    file_id: id,
  }).then((res) => {
    // loading.value = false
    if (res.is_end) {
      stopPolling()
      if (res.error) {
        errorTipText.value = res.error
        uploadError.value = true
        resolving.value = false
        // ToastUtils.error(res.error)
      } else {
        // ToastUtils.success('上传成功')
        successfulType.value = true
        resolving.value = false
        formState.value.version = res.version ?? ''
        formState.value.imprint = res.imprint ?? ''
      }
    } else {
      // loading.value = true
    }
    return res
  })
}
function stopPolling() {
  if (pollIntervalId) {
    clearInterval(pollIntervalId)
  }
}
// 获取版本号 版本说明等信息
// function getDetail(data: string) {
//   const id = data.substring(data.lastIndexOf('/') + 1)
//   loading.value = true
//   getApiNodeVersionDetailApi({
//     file_id: id
//   })
//     .then((res) => {
//       loading.value = false
//       formState.value.version = res.version ?? ''
//       formState.value.imprint = res.imprint ?? ''
//       resolving.value = false
//       //markdownContent.value = marked(res.imprint || '')
//     })

//     .finally(() => {
//       loading.value = false
//     })
// }

// const isUnClick = ref(true)

// 清空表单
function resetField() {
  formRef.value?.resetFields()
  formState.value = {
    imprint: '',
    version: '',
    file_key: '',
    file: undefined,
    id: undefined,
  }
  fileList.value = []
}

function handleClose() {
  pauseUpload()
  resetField()
  emit('reload')
  visible.value = false
}

onUnmounted(() => {
  clearInterval(pollIntervalId)
})

watchEffect(() => {
  if (!visible.value) {
    clearInterval(pollIntervalId)
    resolving.value = false
    successfulType.value = false
  }
})

function handleDelete() {
  console.log('删除')
  pauseUpload()
  resetField()
  percentage.value = 0
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    title="上传节点包"
    :width="480"
    :mask-closable="false"
    :before-close="handleClose"
    :footer="false"
  >
    <!-- <template #footer>
      <a-button @click="handleClose">
        关闭
      </a-button>
    </template> -->
    <a-spin
      :loading="loading"
      class="w-full"
    >
      <a-form
        ref="formRef"
        layout="vertical"
        :model="formState"
      >
        <a-form-item
          label=""
          asterisk-position="end"
        >
          <template #label>
            <div class="flex flex-col">
              <span>节点包</span>
            </div>
          </template>
          <div class="w-full">
            <div>
              <!-- ref="upload" -->
              <a-upload
                v-model:file-list="fileList"
                class="flex-1"
                :multiple="false"
                :before-upload="beforeUpload"
                :custom-request="customRequest"
                :on-before-upload="
                  () => {
                    fileList = []
                    return true
                  }
                "
                accept="application/x-gzip"
                :show-file-list="false"
                :max-count="1"
              >
                <template #upload-button>
                  <a-button
                    type="outline"
                    :disabled="fileList.length > 0 && !uploadError"
                  >
                    <i-icons-upload class="mr-1" />

                    <span class="text-1 text-xs text-[#1D2129] leading-5">点击上传</span>
                  </a-button>
                </template>
              </a-upload>
              <div class="text-5 text-xs text-[#86909C] leading-5">
                仅支持文件格式：.tar.gz
              </div>

              <div
                v-for="i in fileList"
                :key="i"
                class="flex flex-col"
              >
                <div class="progress-row">
                  <div class="progress-name">
                    <i-icons-file />
                    {{ i.name }}
                  </div>
                  <div class="progress-status">
                    <i-icons-version-error v-if="uploadError" />
                    <div>
                      <template v-if="successfulType">
                        <i-icons-success v-if="percentage === 100" />
                      </template>
                      <template v-if="resolving">
                        <i-icons-applying class="rotate-infinite mr-1" />
                        <span class="text-3 text-xs leading-5">解析中...</span>
                      </template>
                      <template v-else>
                        <!-- <i-icons-success v-if="percentage === 100" /> -->
                        <span
                          v-if="percentage !== 100"
                          class="mr-1 text-xs"
                        >{{
                          `${percentage}%`
                        }}</span>
                        <span v-if="percentage !== 100 && percentage !== 0"><i-icons-delete
                          color="#86909C"
                          class="cursor-pointer text-xs"
                          @click="handleDelete"
                        /></span>
                      </template>
                    </div>
                  </div>
                </div>
                <span
                  v-if="uploadError"
                  class="text-xs text-danger leading-5"
                >
                  {{ errorTipText }}
                </span>
                <a-progress
                  v-if="showProgress"
                  :percent="percentage / 100"
                  track-color="165DFF"
                  :show-text="false"
                />
                <div class="flex-1" />
              </div>
            </div>
          </div>
        </a-form-item>

        <a-form-item
          label="版本号"
          field="dns_api_id"
          asterisk-position="end"
        >
          <!-- <a-input v-model="formState.version" disabled placeholder="根据上传文件自动生成"
            class="textarea-color item-disabled-color text-[#1D2129]" /> -->

          <a-input
            v-model="formState.version"
            placeholder="根据上传文件自动生成"
            disabled
            show-word-limit
            class="textarea-color"
          />
        </a-form-item>

        <a-form-item
          label=" 版本说明"
          asterisk-position="end"
        >
          <a-textarea
            v-model="formState.imprint"
            class="textarea-color text-[#1D2129]"
            disabled
            placeholder="根据上传文件自动生成"
            :auto-size="{ maxRows: 5, minRows: 5 }"
          />
        </a-form-item>

        <!-- <a-form-item label="版本说明" asterisk-position="end">
          <div class="imprint-detail"><div v-html="markdownContent"></div></div>
        </a-form-item> -->
      </a-form>
    </a-spin>
  </resource-dialog>
</template>

<style lang="less" scoped>
// .arco-input-group {
//   .cloud-diverse-select {
//     border: 1px solid #d9d9d9;

//     border-radius: 0px 4px 4px 0px;
//     border-top: 1px solid var(---color-border-4, #dfe2e5);
//     border-right: 1px solid var(---color-border-4, #dfe2e5);
//     border-bottom: 1px solid var(---color-border-4, #dfe2e5);
//     background: var(---color-fill-1, #f7f8fa);
//   }
// }
.cloud-diverse-select {
  :deep(.arco-input-prepend) {
    border-radius: 8px 0px 0px 8px;
    border-top: 1px solid var(--border-2, #e5e6eb);
    border-left: 1px solid var(--border-2, #e5e6eb);
    border-bottom: 1px solid var(--border-2, #e5e6eb);
  }

  :deep(.arco-select-view) {
    padding-left: 4px;
    border-left: none;
  }
}

.textarea-color {
  background: var(--fill-1, #f7f8fa) !important;
  :deep(.arco-textarea) {
    // -webkit-text-fill-color: var(--text-1, #1D2129)!important;
    color: #1d2129 !important;
  }
  :deep(.arco-input) {
    //-webkit-text-fill-color: var(--text-1, #1D2129)!important;
  }
}

.progress-row {
  display: flex;
  padding: 4px;
  align-items: center;
  gap: 16px;
  align-self: stretch;
  .progress-name {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1 0 0;
  }
  .progress-status {
    display: flex;
    align-items: center;
  }
}

.imprint-detail {
  display: flex;
  padding: 8px 12px;
  align-items: flex-start;
  gap: 6px;
  align-self: stretch;
  border-radius: 4px;
  border: 1px solid var(---color-border-4, #dfe2e5);
  background: var(---color-fill-1, #f7f8fa);
  height: 160px;
  overflow-x: hidden;
  overflow-y: auto;
  width: 100%;
}

//元素无限旋转
.rotate-infinite {
  animation: rotate 3s linear infinite;
}
:deep(.arco-input) {
  -webkit-text-fill-color: #1d2129 !important;
  &::placeholder {
    -webkit-text-fill-color: var(--text-4, #c9cdd4);
  }
}

:deep(.arco-textarea) {
  -webkit-text-fill-color: #1d2129;
  &::placeholder {
    -webkit-text-fill-color: var(--text-4, #c9cdd4);
  }
}

:deep(.arco-input-wrapper) {
  &:hover {
    border-color: #e5e6eb !important;
  }
}
</style>
